package com.transcargo.request;

import com.transcargo.action.ServletParametersException;
import com.transcargo.action.ServletValidationException;
import com.transcargo.users.UserNotFoundException;
import com.transcargo.rpc.RPCOutput;
import com.transcargo.rating.Rating;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.PrintWriter;
import java.io.IOException;

/**
 * Date: 24.04.2011
 * Time: 17:44:48
 */
public class GetRatingRequest extends Request
{
	private String rid = "";
	private String xml = "";

    private void servletGetValues(HttpServletRequest request) throws ServletParametersException {
		rid = request.getParameter("rid");
		if (rid == null) rid = "";
    }
    private void servletValidateValues() throws ServletValidationException {
    	if (rid.length() == 0) throw new ServletValidationException("Empty rid");
    }
    private void servletExecuteRequest() throws ServletRequestException {
    	try {
    		Rating rating = new Rating(Integer.parseInt(rid), dbase);
    		xml =  RPCOutput.generate(rating);
    	} catch (UserNotFoundException e) {
    		throw new ServletRequestException();
		}
    }
    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        PrintWriter out = null;
		try {
            out = response.getWriter();
            servletGetValues(request);
            servletValidateValues();
            servletExecuteRequest();
            out.println(xml);
	    } catch (ServletParametersException e) {
           sendRedirect(response, "index.jsp");
        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletRequestException e) {
            String xml =  RPCOutput.generate(false);
            out.println(xml);
        }  catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
        }
    }
}